package com.restaurantonlineorder.oauth.filter;

import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 熊宇
 * @date 2022/7/20 15:13
 * @description
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    public static final String SPRING_SECURITY_FORM_PHONE_KEY = "phone";

    private String phoneParameter = SPRING_SECURITY_FORM_PHONE_KEY;


    public LoginFilter(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String phone = obtainPhone(request);
        String password = obtainPassword(request);

        if (phone == null) {
            phone = "";
        }

        if (password == null) {
            password = "";
        }

        phone = phone.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(phone, password);

        //进行认证功能
        return this.getAuthenticationManager().authenticate(authRequest);
    }


    @Nullable
    protected String obtainPhone(HttpServletRequest request) {
        return request.getParameter(phoneParameter);
    }


}
